<template>
    <div class="container">
        <div class="header-actions">
            <el-button type="primary" class="createBtn" @click="createRow">新增轮播图</el-button>
        </div>

        <el-table :data="tableData.data" style="width: 100%;margin-top: 20px;">
            <el-table-column prop="id" label="ID" width="100"></el-table-column>
            <el-table-column prop="title" label="主题" width="150"></el-table-column>
            <el-table-column prop="desciption" label="描述" width="150"></el-table-column>
            <el-table-column prop="imageUrl" label="图片">
                <template #default="scope">
                    <el-image :src="scope.row.imageUrl" alt="轮播图"
                        style="width: 200px; height: 100px; border-radius: 4px;" fit="cover" />
                </template>
            </el-table-column>
            <el-table-column prop="sortOrder" label="顺序" width="100"></el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button size="small" type="primary" plain @click="writeRow(scope.$index)">编辑</el-button>
                    <el-popconfirm title="确认要删除这条轮播图吗?" @confirm="deleteRow(scope.row.id)" confirm-button-text="确定"
                        cancel-button-text="取消">
                        <template #reference>
                            <el-button size="small" type="danger" plain>删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            :current-page="currentPage" @current-change="handlePageChange" @size-change="handlePageSizeChange"
            style="margin-top: 20px;" />

        <!-- 创建轮播图表单 -->
        <el-dialog v-model="isCreate" title="新增轮播图" width="600px">
            <el-form :model="createForm" label-width="80px">
                <el-form-item label="主题">
                    <el-input v-model="createForm.title" placeholder="请输入主题" maxlength="10" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="createForm.desciption" type="textarea" :rows="3" placeholder="请输入描述内容"
                        maxlength="20" show-word-limit>
                    </el-input>
                </el-form-item>
                <el-form-item label="轮播图">
                    <el-upload class="upload-demo" action="http://localhost:9090/api/upload/image"
                        :on-success="handleCreateUploadSuccess" :before-upload="beforeUpload" :show-file-list="false">
                        <div class="upload-container">
                            <div v-if="createForm.imageUrl" class="preview-container">
                                <el-image :src="createForm.imageUrl" fit="cover" class="preview-image" />
                                <div class="image-overlay">
                                    <el-icon class="upload-icon"><upload-filled /></el-icon>
                                    <span class="upload-text">更换图片</span>
                                </div>
                            </div>
                            <div v-else class="upload-placeholder">
                                <el-icon class="upload-icon">
                                    <plus />
                                </el-icon>
                                <span class="upload-text">点击上传轮播图</span>
                                <span class="upload-desc">支持 JPG/PNG 格式</span>
                            </div>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="顺序">
                    <el-input-number v-model="createForm.sortOrder" :min="1"
                        controls-position="right"></el-input-number>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="isCreate = false">取消</el-button>
                    <el-button type="primary" @click="realyCreate">确认</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 修改轮播图表单 -->
        <el-dialog v-model="isWrite" title="修改轮播图" width="600px">
            <el-form :model="editForm" label-width="80px">
                <el-form-item label="ID">
                    <el-input v-model="editForm.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="主题">
                    <el-input v-model="editForm.title" placeholder="请输入主题" maxlength="10" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="editForm.desciption" type="textarea" :rows="3" placeholder="请输入描述内容"
                        maxlength="20" show-word-limit>
                    </el-input>
                </el-form-item>
                <el-form-item label="轮播图">
                    <el-upload class="upload-demo" action="http://localhost:9090/api/upload/image"
                        :on-success="handleEditUploadSuccess" :before-upload="beforeUpload" :show-file-list="false">
                        <div class="upload-container">
                            <div v-if="editForm.imageUrl" class="preview-container">
                                <el-image :src="editForm.imageUrl" fit="cover" class="preview-image" />
                                <div class="image-overlay">
                                    <el-icon class="upload-icon"><upload-filled /></el-icon>
                                    <span class="upload-text">更换图片</span>
                                </div>
                            </div>
                            <div v-else class="upload-placeholder">
                                <el-icon class="upload-icon">
                                    <plus />
                                </el-icon>
                                <span class="upload-text">点击上传轮播图</span>
                                <span class="upload-desc">支持 JPG/PNG 格式</span>
                            </div>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="顺序">
                    <el-input-number v-model="editForm.sortOrder" :min="1" controls-position="right"></el-input-number>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="isWrite = false">取消</el-button>
                    <el-button type="primary" @click="realyWrite">确认</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, UploadFilled } from '@element-plus/icons-vue'

const baseURL = 'http://localhost:9090/carousel';

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = reactive({ data: [] });

const isCreate = ref(false);
const isWrite = ref(false);

const createForm = reactive({
    imageUrl: '',
    sortOrder: 1,
    title: '',
    desciption: ''
});

const editForm = reactive({
    id: '',
    imageUrl: '',
    desciption: '',
    title: '',
    sortOrder: 1
});

const handlePageChange = (page: number) => {
    currentPage.value = page;
    fetchTableData();
}

const handlePageSizeChange = (size: number) => {
    pageSize.value = size;
    fetchTableData();
}

function fetchTableData() {
    axios.get(`${baseURL}/page`, {
        params: {
            pageNum: currentPage.value,
            pageSize: pageSize.value
        }
    }).then((res) => {
        tableData.data = res.data.records;
        total.value = res.data.total;
    }).catch(error => {
        ElMessage.error('加载数据失败');
    });
}

// 初始加载数据
fetchTableData();

function deleteRow(id: number) {
    ElMessageBox.confirm('确认要删除这条轮播图吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        axios.delete(`${baseURL}/delete/${id}`).then(() => {
            fetchTableData();
            ElMessage.success('删除成功');
        }).catch(() => {
            ElMessage.error('删除失败');
        });
    }).catch(() => {
        // 取消删除操作
    });
}

function createRow() {
    createForm.imageUrl = '';
    createForm.sortOrder = 1;
    isCreate.value = true;
}

function realyCreate() {
    if (!createForm.imageUrl) {
        ElMessage.warning('请上传轮播图');
        return;
    }
    console.log(createForm);
    axios.post(`${baseURL}/add`, createForm).then(() => {
        fetchTableData();
        isCreate.value = false;
        ElMessage.success('新增成功');
    }).catch(() => {
        ElMessage.error('新增失败');
    });
}

function writeRow(index: number) {
    const item = tableData.data[index];
    editForm.id = item.id;
    editForm.imageUrl = item.imageUrl;
    editForm.sortOrder = item.sortOrder;
    editForm.title = item.title;
    editForm.desciption = item.desciption;
    isWrite.value = true;
}

function realyWrite() {
    if (!editForm.imageUrl) {
        ElMessage.warning('请上传轮播图');
        return;
    }
    axios.put(`${baseURL}/update`, editForm).then(() => {
        fetchTableData();
        isWrite.value = false;
        ElMessage.success('修改成功');
    }).catch(() => {
        ElMessage.error('修改失败');
    });
}

const handleCreateUploadSuccess = (response: any) => {
    createForm.imageUrl = "http://localhost:9090/api/upload/uploads/" + response;
    ElMessage.success('图片上传成功');
}

const handleEditUploadSuccess = (response: any) => {
    editForm.imageUrl = "http://localhost:9090/api/upload/uploads/" + response;
    ElMessage.success('图片上传成功');
}

const beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG && !isPNG) {
        ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
        return false;
    }
    return true;
}
</script>

<style scoped>
.container {
    padding: 20px;
}

.header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.el-pagination {
    display: flex;
    justify-content: center;
}

.el-pagination .el-pager li.is-active {
    background-color: #409EFF;
    color: white;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.upload-container {
    width: 100%;
    height: 200px;
    border: 2px dashed #dcdfe6;
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s;
    cursor: pointer;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.upload-container:hover {
    border-color: #409EFF;
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.preview-container {
    width: 100%;
    height: 100%;
    position: relative;
}

.preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s;
}

.preview-container:hover .preview-image {
    transform: scale(1.05);
}

.image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    opacity: 0;
    transition: opacity 0.3s;
    backdrop-filter: blur(2px);
}

.preview-container:hover .image-overlay {
    opacity: 1;
}

.upload-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #909399;
    background: #f5f7fa;
    transition: background-color 0.3s;
}

.upload-placeholder:hover {
    background: #eef1f6;
}

.upload-icon {
    font-size: 36px;
    margin-bottom: 12px;
    color: #409EFF;
    transition: transform 0.3s;
}

.upload-container:hover .upload-icon {
    transform: scale(1.1);
}

.upload-text {
    font-size: 16px;
    color: #ffffff;
    margin: 8px 0;
    font-weight: 500;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.upload-desc {
    font-size: 13px;
    color: #909399;
    margin-top: 4px;
}

.upload-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
}
</style>